﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace Adams.Web
{
    public class CaptchaResult : ActionResult
    {
        public string RandomWord { get; set; }

        public CaptchaResult(string randomWord)
        {
            RandomWord = randomWord;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            using (Bitmap objBMP = new Bitmap(150, 60))
            {
                using (Graphics objGraphics = Graphics.FromImage(objBMP))
                {
                    objGraphics.Clear(Color.LightGray);

                    using (SolidBrush objBrush = new SolidBrush(Color.Black))
                    {
                        Font objFont = null;
                        string myFont = string.Empty;
                        string str = string.Empty;

                        string[] crypticFonts = new string[]{
                            "Arial",
                            "Verdana",
                            "Comic Sans MS",
                            "Impact",
                            "Haettenschweiler",
                            "Lucida Sans Unicode",
                            "Garamond",
                            "Courier New",
                            "Book Antiqua",
                            "Arial Narrow",
                            "Estrangelo Edessa",
                        };

                        for (int a = 0; a <= RandomWord.Length - 1; a++)
                        {
                            myFont = crypticFonts[new Random().Next(a)];
                            objFont = new Font(myFont, 18, FontStyle.Bold | FontStyle.Italic | FontStyle.Strikeout);
                            str = RandomWord.Substring(a, 1);
                            objGraphics.DrawString(str, objFont, objBrush, a * 20, 20);
                            objGraphics.Flush();
                        }

                        context.HttpContext.Response.ContentType = "image/GIF";
                        objBMP.Save(context.HttpContext.Response.OutputStream, ImageFormat.Gif);
                        objFont.Dispose();
                    }
                }
            }
        }
    }
}